<?php
class PostController extends Controller {
	
	
	public function index($param) {
		$this->getSmarty ();

		
		$postid = $param['id'];
        require_once COMMON . DS  . 'Constant.class.php';
        $this->smarty->assign ( 'pagesets', Constant::postHeader($postid));


		require_once SERVICE . DS . 'PostService.class.php';
		$service = new PostService ( $this->getDB () );
		
		$postelement = $service->getPost ( $postid );
		$postComents = $service->getComments ( $postid );
		
		$data = array ();
		foreach ( $postComents as $re ) {
			
			$photo;
			if (empty ( $re->user_photo )) {
				$photo = "public/photo/user-iocn.gif";
			} else {
				$photo = $re->user_photo;
			}
			
			$data [] = array (
					"user_photo" => $photo,
					"username" => empty($re->username)? "游客":$re->username,
					"comment_ID" => $re->comment_ID,
					"comment_date" => $re->comment_date,
					"comment_content" => $re->comment_content,
					"rownum" => $re->rownum
			);
		}
		$post = $postelement [0];
		//设置上一篇内容
		$propost = $service->getPrePost ( $postid );
		//设置下一篇内容
		$nxtpost = $service->getNxtPost( $postid );
        $preAndnxt = array($propost[0],$nxtpost[0]);
        require_once SERVICE . DS . 'IndexService.class.php';
        $indexService = new IndexService( $this->getDB () );
//         $indexService->fillPostHref($preAndnxt);
        $propost = $preAndnxt[0];
        $nxtpost =  $preAndnxt[1];
        if(!empty($propost)){

            //设置上一篇内容
            $pre_post =  array (
                "url" =>  WEBSITE_URL."post".DS."index?id=".$propost->ID,
                "name" => $propost->post_title
            );
        }else{
            $pre_post =  array (
                "url" =>  WEBSITE_URL."blog",
                "name" => "这是第一篇"
            );
        }
		if(!empty($nxtpost)){

			//设置下一篇内容
			$nxt_post =  array (
					"url" =>WEBSITE_URL."post".DS."index?id=".$nxtpost->ID,
					"name" => $nxtpost->post_title
			);
		}else{
			$nxt_post =  array (
					"url" => WEBSITE_URL."blog",
					"name" => "已经是最后一篇了"
			);
		}
		
		$tagarr = $service->getTagIdByName($postid);
		if (! empty ( $tagarr )) {
			foreach ( $tagarr as $tag ) {
				$tagdata [] = array (
						"url" => WEBSITE_URL."tag/showtag/".$tag->tag_id,
						"name" => $tag->tag_name 
				);
			}
		}
		 
		
		$lastcomments = $service->getnewComments($postid);
		
		foreach ( $lastcomments as $re ) {
				
			$photo;
			if (empty ( $re->user_photo )) {
				$photo = "public/photo/user-iocn.gif";
			} else {
				$photo = $re->user_photo;
			}
				
			$lastcommentsdatas [] = array (
					"user_photo" => $photo,
					"username" => empty($re->username)? "游客":$re->username,
					"comment_ID" => $re->comment_ID,
					"comment_date" => $re->comment_date,
					"comment_content" => $re->comment_content,
					"rownum" => $re->rownum
			);
		}
		
		$this->smarty->assign ( 'postComents', $data );
		$this->smarty->assign ( 'comentcount', count($data) );
		$this->smarty->assign ( 'postelement', $post );
		$this->smarty->assign ( 'posttags', $tagdata );
		$this->smarty->assign ( 'post', $post );
        //热门标签
        require_once COMMON . DS  . 'Constant.class.php';
        $this->smarty->assign ( 'tags',Constant::getHotTag() );
        $this->smarty->assign ( 'crumb', Constant::getSecCategoryNav($post->post_category) );
        $this->smarty->assign ( 'blogcats', Constant::getCategorylist() );
		$this->smarty->assign ( 'pre_post', $pre_post );
		$this->smarty->assign ( 'nxt_post', $nxt_post );
		$this->smarty->assign ( 'lastcomments', $lastcommentsdatas );
		$this->smarty->assign ( 'postid', $postid );
        $this->smarty->assign ( 'pagesets', Constant::indexHeader() );
		$this->smarty->display ( "blogitem.tpl" );
	}
	public function updateLoadCounts() {
		$postid = $_POST ['id'];
		require_once SERVICE . DS . 'PostService.class.php';
		$service = new PostService ( $this->getDB () );
		$clickNum = $service->updateViewCounts ( $postid );
        $result = array(
                      "clickNum" =>$clickNum);
        echo json_encode ( $result );
	}
	function getIP() {
		global $ip;
		if (getenv ( "HTTP_CLIENT_IP" ))
			$ip = getenv ( "HTTP_CLIENT_IP" );
		else if (getenv ( "HTTP_X_FORWARDED_FOR" ))
			$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
		else if (getenv ( "REMOTE_ADDR" ))
			$ip = getenv ( "REMOTE_ADDR" );
		else
			$ip = "Unknow";
		return $ip;
	}
	public function getPraiseCount() {
		echo 100;
	}
	public function getComments() {
		echo 100;
	}

	/**
	 * 发表评论：这里前后台使用ajax的数据交换格式，那么这个方法必须要返回ajax格式的
	 */
	public function savePostComments() {
		$this->getSmarty ();
		require_once SERVICE . DS . 'PostService.class.php';
 		$service = new PostService ( $this->getDB () );
  		$user = $_SESSION ['user'];
// 		// 如果不是post方式的提交，直接转向
// 		if (empty ( $user )) {
// 			$result = array (
// 					success => false 
// 			);
// 			// echo的作用只是打印，不会结束方法的执行
// 			echo json_encode ( $result );
// 			return;
// 		}
		$userid = null;
		$username = null;
  		if (empty ( $user )) {
  			$username = "游客";
  		}else{
  			$userid = $user->userid;
  			$username = $user->username;
  		}
		$postid = $_POST ['id'];
		$ip = self::getIP ();
		$msg = strip_tags ( $_POST ['postMessage'] );
		$sql = "INSERT INTO post_comments(comment_post_ID,user_id,comment_content,comment_date,comment_author_IP,comment_approved) VALUES('$postid','$userid','$msg',SYSDATE(),'$ip',1)";
		$service->savePostComments ( $sql );
        if (empty ( $user->user_photo )) {
            $photo = "public/photo/user-iocn.gif";
        } else {
            $photo = $user->user_photo;
        }
        
       $countsql = "SELECT COUNT(*) FROM   post_comments p    WHERE  comment_approved = 0 AND comment_post_ID='296'" ;
       $count = $this->dbutil->get_var ( $countsql );
        $commentsArray = array(
             "user_poto" =>$photo,
             "username" =>$username,
             "comment_date" =>date("Y-m-d H:i:s"),
             "comment_content" =>$msg,
        	 "rownum" =>$count+1,
        		
        );
		$result = array (
				success => true,
                comment=>$commentsArray
		);
		// echo的作用只是打印，不会结束方法的执行
		echo json_encode ( $result );
	}
    //小孙，为什么不看我的注释。。你这里是一个ajax的调用，设置的是返回json
    //但是你返回的不是，所以前台接不到返回数据
	public function updateAgreeCounts() {
        ob_start();
        require_once SERVICE . DS . 'PostService.class.php';
		$service = new PostService ( $this->getDB () );
		$poid = $_POST ["id"];
		$ip = self::getIP ();
		$key = md5 ( $ip . $poid );
		$cookie_key = $_COOKIE [$key];
        echo $cookie_key;
        $returnData = -1;
		if (empty ( $cookie_key )) {
			//setcookie ( $key, "ready" );
			$result = $service->updateAgreeCounts ( $poid );
            $returnData=$result [0]->agree_count;
		}
      echo  json_encode(array("result"=>$returnData,"key"=>$key));
	}
    //小孙，为什么不看我的注释。。你这里是一个ajax的调用，设置的是返回json
    //但是你返回的不是，所以前台接不到返回数据
    public function getAgreeCounts() {
        ob_start();
        require_once SERVICE . DS . 'PostService.class.php';
        $service = new PostService ( $this->getDB () );
        $poid = $_POST ["id"];
        $ip = self::getIP ();
        $key = md5 ( $ip . $poid );
        $returnData = -1;
        if (empty ( $cookie_key )) {
            //setcookie ( $key, "ready" );
            $result = $service->getAgreeCounts ( $poid );
            $returnData=$result;
        }
        echo  json_encode(array("result"=>$returnData,"key"=>$key));
    }
	public function headerDatas() {
		require_once COMMON . DS . 'Constant.class.php';
		$js = array (
				WEBSITE_URL . "public/js/posts/post.js" 
		);
		// $css = array(WEBSITE_URL."public/assets/css/validationEngine.jquery.css");
		// $pagesets = array("seo"=>Constant::$seoarray,"js"=>$js,"css"=>$css,"nav"=>Constant::getNav());
		$pagesets = array (
				"seo" => Constant::$seoarray,
				"js" => $js,
				"nav" => Constant::getNav () 
		);
		return $pagesets;
	}
}